package com.lf.freezingpoint.common.security.userdetails;

import com.lf.freezingpoint.entity.SysUser;
import com.lf.freezingpoint.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@Service
public class SysUserDetailsServiceImpl implements UserDetailsService {
    private static final Logger logger = Logger.getLogger(SysUserDetailsServiceImpl.class.toString());

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetails userDetails = null;
        SysUser sysUser = sysUserService.getSysUserInfoByUsername(username);

        if (null != sysUser) {
            List<String> roles = new ArrayList<>();
            sysUser.getRoles().forEach(role -> roles.add(role.getRoleKey()));

            String[] role = roles.toArray(new String[roles.size()]);

            userDetails = User
                    .withUsername(sysUser.getUsername())
                    .password(sysUser.getPassword())
                    .disabled("1".equals(sysUser.getStatus()))
                    .roles(role)
                    .build();
        }

        if (userDetails == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        } else if (!userDetails.isEnabled()) {
            throw new DisabledException("该账户已被禁用");
        }

        logger.info("loadUserByUsername认证:" + userDetails.toString());
        return userDetails;
    }
}
